import { useApi } from '@/hooks/useApi';
import { mockLogin, mockUserInfo } from '@/services/api';
import type { MenuResponse, UserInfo } from '@/services/modules';
import { defineStore } from 'pinia';
import { ref } from 'vue';


export const useUserStore = defineStore('user', {
  state: () => {
    const token = ref('');
    const userInfo = ref<UserInfo | null>(null);
    const menuList = ref<MenuResponse[]>([]);
    const { loading, run: loginRun } = useApi(
      mockLogin,
      {},
      {
        immediate: false,
        // isErrorTip: true,
        isSuccessTip: true,
        onSuccess: (data: any) => {
          setToken(data.token);
          setUserInfo(data.userInfo);
          window.location.reload();
        },
      }
    );
    const { run: userInfoRun } = useApi(
      mockUserInfo,
      {},
      {
        immediate: false,
        onSuccess: (data: any) => {
          setUserInfo(data.userInfo);
        },
      }
    );
    const setToken = (code: string) => {
      token.value = code;
      localStorage.setItem('token', code);
    };
    const setUserInfo = (userInfo: Record<string, any>) => {
      userInfo.value = userInfo;
    };

    const login = (params: Record<string, any>) => {
      loginRun(params);
    };
    const getUserInfo = () => {
      userInfoRun();
    };

    const setMenuList = (menus: MenuResponse[]) => {
      menuList.value = menus;
    };

    const getMenuList = () => {
      return menuList.value;
    };
    return {
      token,
      userInfo,
      menuList,
      loading,
      login,
      getUserInfo,
      setMenuList,
      getMenuList,
    };
  },
});
